package com.ahui.ydd.controller;

import com.ahui.ydd.Vo.*;
import com.ahui.ydd.common.CustomException;
import com.ahui.ydd.common.R;
import com.ahui.ydd.common.ResultData;
import com.ahui.ydd.entity.YddArticle;
import com.ahui.ydd.entity.YddCate;
import com.ahui.ydd.entity.YddUser;
import com.ahui.ydd.entity.YddUserData;
import com.ahui.ydd.service.YddArticleService;
import com.ahui.ydd.service.YddCateService;
import com.ahui.ydd.service.YddUserDataService;
import com.ahui.ydd.service.YddUserService;
import com.ahui.ydd.utils.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.smartcardio.CardException;
import java.sql.SQLWarning;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private YddArticleService yddArticleService;
    @Autowired
    private YddUserService yddUserService;
    @Autowired
    private YddUserDataService yddUserDataService;
    @Autowired
    private YddCateService yddCateService;

    /**
     * 根据token获取用户id
     *
     * @param request HttpServletRequest接口
     * @return
     */
    private Integer getTokenId(HttpServletRequest request) {
        //获取token
        String token = request.getHeader("token");
        Claims claims = JwtUtils.getClaims(token);
        //通过token获得用户id
        return (Integer) claims.get("Userid");
    }

    /**
     * 登录之后跳转页面
     *
     * @param request
     * @return
     */
    @GetMapping("/getUserInfo")
    public ResultData getUserInfo(HttpServletRequest request) {

        //获取token
        Integer userId = getTokenId(request);

        //用户发表文章数量
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddArticle::getUserId, userId);
        int count = yddArticleService.count(queryWrapper);

        //点赞 2
        LambdaQueryWrapper<YddUserData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null, YddUserData::getUserId, userId)
                .eq(YddUserData::getType, 2);
        int zanNum = yddUserDataService.count(wrapper);

        //收藏 1
        LambdaQueryWrapper<YddUserData> wrapper1 = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null, YddUserData::getUserId, userId)
                .eq(YddUserData::getType, 1);
        int collectNum = yddUserDataService.count(wrapper1);

        //用户信息
//        LambdaQueryWrapper<YddUser> wrapper2 = new LambdaQueryWrapper<>();
//        wrapper2.eq(YddUser::getId,userId);
        YddUser yddUser = yddUserService.getById(userId);

        //封装对象
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setUserInfo(yddUser);
        userInfoVo.setArticleNum(count);
        userInfoVo.setZanNum(zanNum);
        userInfoVo.setZanNum(collectNum);

        return ResultData.ok("", userInfoVo);
    }

    /**
     * 我的文章
     *
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping("/myArticle")
    public ResultData myArticle(int page, int limit, HttpServletRequest request) {
        //创建分页构造器
        Page<YddArticle> pageInfo = new Page<>(page, limit);
        //根据token获取id
        Integer userId = getTokenId(request);

        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddArticle::getUserId, userId);

        MyArticleVo articlePage = yddArticleService.selectByMyArticlePage(pageInfo, queryWrapper);

        return ResultData.ok("", articlePage);
    }

    /**
     * 我的收藏/我的点赞
     *
     * @param page
     * @param limit
     * @param type  1 收藏  2 点赞
     * @return
     */
    @GetMapping("/userDataList")
    public ResultData userDataList(int page, int limit, int type, HttpServletRequest request) {
        //创建分页构造器
        Page<YddArticle> pageInfo = new Page<>(page, limit);
        //根据token获取id
        Integer userId = getTokenId(request);
        //查询ydd_user_data表格
        //select * from YddUserData where user_id = ? and type = ?;
        LambdaQueryWrapper<YddUserData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(YddUserData::getArticleId)
                .eq(YddUserData::getUserId, userId)
                .eq(YddUserData::getType, type);
        List<YddUserData> userData = yddUserDataService.list(queryWrapper);

        /*int[] ids = new int[userData.size()];
        int count = 0;
        for (YddUserData userDatum : userData) {
            ids[count] = userDatum.getArticleId();
            count++ ;
        }*/

        List<Integer> ids = new ArrayList<>();
        for (YddUserData userDatum : userData) {
            ids.add(userDatum.getArticleId());
        }

        //查询ydd_article
        //select * from ydd_article where user_id = ? and id in (?,?,?);
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(YddArticle::getId,ids);
        Page<YddArticle> articlePage = yddArticleService.page(pageInfo, wrapper);
        //获取 articlePage 中 records 集合数据
        List<YddArticle> records = articlePage.getRecords();
        List<YddArticleCateVo> collect = records.stream().map((item) -> {
            YddArticleCateVo vo = new YddArticleCateVo();
            //将records 中数据 复制到vo中
            BeanUtils.copyProperties(item, vo);
            //根据Cateid来查询gCateName
            YddCate yddCate = yddCateService.getById(item.getCateid());
            vo.setCatename(yddCate.getCatename());
            return vo;
        }).collect(Collectors.toList());

        //将数据放入maos集合
        Map<String,  Object> maps = new HashMap<>();
        maps.put("data", collect);

        //创建收集数据收据对象
        userDataListVo userDataListVo = new userDataListVo();
        userDataListVo.setCount(articlePage.getTotal());             //总条数
        userDataListVo.setTotalPages(articlePage.getPages());        //总页数
        userDataListVo.setPageSize(articlePage.getSize());           //显示几条数据
        userDataListVo.setCurrentPage(articlePage.getCurrent());     //显示的页数
        userDataListVo.setList(maps);  //data
        return ResultData.ok("", userDataListVo);
    }

    /**
     * 修改文章
     * @param yddArticle
     * @param request
     * @return
     */
    @PostMapping("/editArticle")
    public R editArticle(@RequestBody YddArticle yddArticle, HttpServletRequest request){

        LambdaUpdateWrapper<YddArticle> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(YddArticle::getUserId,getTokenId(request))
                .eq(YddArticle::getId,yddArticle.getId());
        YddArticle article = new YddArticle();
        article.setUserId(getTokenId(request));
        boolean res = yddArticleService.update(wrapper);

        if (!res) {
            throw new CustomException("操作失败!");
        }
        return R.success("操作成功!");
    }


    /**
     * 修改用户资料
     * @param yddUser
     * @return
     */
    @PostMapping("/update")
    public R update(@RequestBody YddUser yddUser,  HttpServletRequest request) {
        LambdaUpdateWrapper<YddUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(YddUser::getId, yddUser.getId())
                .eq(YddUser::getId, getTokenId(request));
        boolean res = yddUserService.update(yddUser, wrapper);
        if (!res) {
            throw new CustomException("操作失败!");
        }
        return R.success("操作成功!");
    }

    /**
     * 点赞/取消点赞和收藏/取消收藏
     *
     * @param type       1 收藏  2 点赞
     * @param article_id 文章id
     * @param action     add表示 点赞或收藏， del表示取消点赞或取消收藏
    //     * @param request    token秘钥
     * @return
     */
    @GetMapping("/userDataHandle")
    public R userDataHandle(int type, String action, int article_id, HttpServletRequest request) {
        //获取token  通过token获得用户id
        Integer userId = getTokenId(request);
        log.info("用户id" + userId);

        //删除条件
        LambdaQueryWrapper<YddUserData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddUserData::getArticleId, article_id)
                .eq(YddUserData::getUserId, userId);
        //封装对象
        YddUserData yddUserData = new YddUserData();
        yddUserData.setArticleId(article_id);
        yddUserData.setUserId(userId);
        yddUserData.setType(type);
        //判断用户操作
        if (action.equals("add")) { //点赞或收藏
            if (type == 1) {// 收藏
                yddUserDataService.save(yddUserData);
            } else { //点赞
                yddUserDataService.save(yddUserData);
            }
        } else if (action.equals("del")) { //取消点赞或取消收藏
            if (type == 1) {// 取消收藏
                yddUserDataService.remove(wrapper);
//                yddArticleService.removeById(article_id);
            } else { //取消点赞
                yddUserDataService.remove(wrapper);
//                yddArticleService.removeById(article_id);
            }
        }
        return R.success("操作成功");
    }

    /**
     * 发布文章
     *
     * @param yddArticle
     * @return
     */
    @PostMapping("/addArticle")
    public R addArticle(@RequestBody YddArticle yddArticle, HttpServletRequest request) {
        Integer userId = getTokenId(request);
        yddArticle.setUserId(userId);
        boolean save = yddArticleService.save(yddArticle);
        if (!save) {
            throw new CustomException("操作失败!");
        }
        return R.success("操作成功!");
    }

    /**
     * 删除我的文章
     *
     * @param id    文章id
     * @return
     */
    @GetMapping("/delArticle")
    public R delArticle(Integer id,  HttpServletRequest request) {
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddArticle::getId, id)
                .eq(YddArticle::getUserId, getTokenId(request));
        boolean res = yddArticleService.removeById(wrapper);
        if (!res) {
            throw new CustomException("操作失败!");
        }
        return R.success("操作成功!");
    }

}
